package com.lujieni.threadpool.decorate;

import com.lujieni.threadpool.config.Context;
import com.lujieni.threadpool.context.ContextHolder;
import org.springframework.core.task.TaskDecorator;

import java.util.concurrent.TimeUnit;

public class CustomTaskDecorator implements TaskDecorator {

    /**
     * Decorate the given {@code Runnable}, returning a potentially wrapped
     * {@code Runnable} for actual execution.
     *
     * @param runnable the original {@code Runnable}
     * @return the decorated {@code Runnable}
     */
    @Override
    public Runnable decorate(Runnable runnable) {
        // tomcat线程下一行代码
        Context context = ContextHolder.getContext();
        // 执行下面代码的线程是线程池中的线程
        return ()->{
           /* try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }*/
            try {
                // 在任务执行之前，将上下文设置到执行任务的线程中
                ContextHolder.setContext(context);
                runnable.run();
            } finally {
                // 清理操作，避免线程池中的线程复用时出现上下文信息泄漏
                ContextHolder.clearContext();
            }
        };
    }
}
